<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Connectors</title>
  <link rel="stylesheet" href="/webui/css/styles.css" />
  <style>
    body { font-family: system-ui, -apple-system, Segoe UI, Roboto, sans-serif; padding: 16px; }
    .row { display: flex; justify-content: space-between; align-items: center; border: 1px solid #e5e7eb; border-radius: 6px; padding: 10px; margin-bottom: 8px; }
    .btn { border-radius: 4px; padding: 6px 10px; cursor: pointer; }
    .btn-primary { background: #2563eb; color: white; }
    .btn-secondary { background: #374151; color: white; }
    .btn-ghost { background: #e5e7eb; }
    .muted { color: #6b7280; font-size: 12px; }
    .grid { display: grid; gap: 8px; }
  </style>
  <script>
    async function api(method, url, body) {
      const opts = { method, headers: { 'Content-Type': 'application/json' } }
      if (body) opts.body = JSON.stringify(body)
      const r = await fetch(url, opts)
      const txt = await r.text()
      let j = null
      try { j = JSON.parse(txt) } catch {}
      if (!r.ok) throw new Error((j && j.detail) || r.statusText || 'Request failed')
      return j
    }
    async function loadProviders() {
      const list = document.getElementById('providers')
      list.innerHTML = ''
      const providers = await api('GET', '/api/v1/connectors/providers')
      providers.forEach(p => {
        const el = document.createElement('div')
        el.className = 'row'
        el.innerHTML = `<div><div><b>${p.name}</b></div><div class="muted">${(p.scopes_required||[]).join(', ')}</div></div><button class="btn btn-primary">Connect</button>`
        el.querySelector('button').onclick = async () => {
          const j = await api('POST', `/api/v1/connectors/providers/${p.name}/authorize`)
          if (j && j.auth_url) window.location.href = j.auth_url
        }
        list.appendChild(el)
      })
    }
    async function loadAccounts() {
      const list = document.getElementById('accounts')
      list.innerHTML = ''
      const accounts = await api('GET', '/api/v1/connectors/accounts')
      accounts.forEach(a => {
        const el = document.createElement('div')
        el.className = 'row'
        el.innerHTML = `<div><div><b>${a.display_name}</b></div><div class="muted">${a.provider}${a.email?(' • '+a.email):''}</div></div><div><button class="btn btn-ghost" data-browse>Browse</button> <button class="btn btn-secondary" data-remove>Remove</button></div>`
        el.querySelector('[data-remove]').onclick = async () => {
          await api('DELETE', `/api/v1/connectors/accounts/${a.id}`)
          await loadAccounts()
        }
        el.querySelector('[data-browse]').onclick = () => browse(a)
        list.appendChild(el)
      })
    }
    async function browse(a) {
      const out = document.getElementById('browse')
      out.innerHTML = ''
      const params = new URLSearchParams({ account_id: String(a.id) })
      const j = await api('GET', `/api/v1/connectors/providers/${a.provider}/sources/browse?`+params.toString())
      (j.items||[]).forEach(it => {
        const el = document.createElement('div')
        el.className = 'row'
        el.innerHTML = `<div><div><b>${it.name || it.id}</b></div><div class="muted">${it.mimeType || it.type || ''}</div></div><button class="btn btn-primary">Add Source</button>`
        el.querySelector('button').onclick = async () => {
          const payload = { account_id: a.id, provider: a.provider, remote_id: it.id, type: (it.is_folder? 'folder' : (it.type || 'page')), path: (it.name||it.id), options: { recursive: true } }
          await api('POST', '/api/v1/connectors/sources', payload)
          await loadSources()
        }
        out.appendChild(el)
      })
    }
    async function loadSources() {
      const list = document.getElementById('sources')
      list.innerHTML = ''
      const sources = await api('GET', '/api/v1/connectors/sources')
      sources.forEach(s => {
        const el = document.createElement('div')
        el.className = 'row'
        el.innerHTML = `<div><div><b>[${s.provider}] ${s.path || s.remote_id}</b></div><div class="muted">${s.type} • ${s.enabled? 'enabled' : 'disabled'}</div></div><div><button class="btn btn-ghost" data-toggle>${s.enabled? 'Disable':'Enable'}</button> <button class="btn btn-primary" data-import>Import</button></div>`
        el.querySelector('[data-toggle]').onclick = async () => {
          await api('PATCH', `/api/v1/connectors/sources/${s.id}`, { enabled: !s.enabled })
          await loadSources()
        }
        el.querySelector('[data-import]').onclick = async () => {
          const j = await api('POST', `/api/v1/connectors/sources/${s.id}/import`)
          const jobId = j?.id
          document.getElementById('jobStatus').textContent = 'Created job '+jobId
          document.getElementById('jobId').value = jobId
        }
        list.appendChild(el)
      })
    }
    async function loadJob() {
      const jobId = (document.getElementById('jobId') as HTMLInputElement).value
      if (!jobId) return
      try {
        const j = await api('GET', `/api/v1/connectors/jobs/${jobId}`)
        document.getElementById('jobStatus').textContent = JSON.stringify(j, null, 2)
      } catch (e) {
        document.getElementById('jobStatus').textContent = 'Failed to load job'
      }
    }
    async function init() {
      await loadProviders(); await loadAccounts(); await loadSources();
    }
    window.addEventListener('DOMContentLoaded', init)
  </script>
</head>
<body>
  <h1>Connectors</h1>
  <h2>Providers</h2>
  <div id="providers" class="grid"></div>
  <h2>Accounts</h2>
  <div id="accounts" class="grid"></div>
  <h2>Browse</h2>
  <div id="browse" class="grid"></div>
  <h2>Sources</h2>
  <div id="sources" class="grid"></div>
  <h2>Job</h2>
  <div class="row">
    <input id="jobId" placeholder="Job ID" />
    <button class="btn btn-secondary" onclick="loadJob()">Refresh</button>
  </div>
  <pre id="jobStatus" class="muted">-</pre>
</body>
</html>
